const { readFileSync, writeFileSync } = require('fs')

; ((async () => {
    const rawData = readFileSync('./data.txt').toString()
    const areas = rawData.split('\n').map(line => {
        const [code, name, fatherCode, level] = line.split(',')
        return {
            code, name, fatherCode, level, cites: [], regions: []
        }
    })

    const emptyDictCity = []
    const emptyCityProvince = []

    const provinces = areas.filter(area => +area.level === 1)
    provinces.forEach(province => {
        const cites = areas
            .filter(area => +area.level === 2)
            .filter(area => area.fatherCode === province.code)
        province.cites = cites
        province.cites.forEach(city => {
            const regions = areas
                .filter(area => +area.level === 3)
                .filter(area => area.fatherCode === city.code)
            city.regions = regions
            if (!regions.length) {
                emptyDictCity.push(city)
            }
        })
        if (!cites.length) {
            emptyCityProvince.push(province)
        }
    })

    console.log(emptyCityProvince)
    console.log('-------')
    console.log(emptyDictCity)


    const body = provinces.map(province => {
        const cityBody = province.cites.map(city => {
            const dictBody = city.regions.map(dict => `put("${dict.name}", "${dict.code}");`).join('\n\t\t\t\t\t\t')
            return `
                put("${city.name}", new HashMap<String, String>()
                    {{
                        ${dictBody}
                    }}
                );
            `
        }).join('')
        return `
        put("${province.name}", new HashMap<String, HashMap<String, String>>()
            {{${cityBody}}}
        );
      `
    }).join('\n')

    const code = `
  static final HashMap areaMap = new HashMap<String, HashMap<String, HashMap<String, String>>>() {{${body}
  }};
  `

    const code2 = emptyDictCity.map(city => `put("${city.name}", "${city.code}");`)
        .join('\n')

    const code3 = emptyCityProvince.map(province => `put("${province.name}", "${province.code}");`)
        .join('\n')
    writeFileSync('./result.txt', code3)

})())